// 用户模型
const mongo_client = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const db_name = 'dc_DB';

// 连接数据库，返回数据库对象
const db_operate = (cb) => {
    mongo_client.connect(url, (err, client) => {
        if (err) {
            console.log(err);
        }
        const db =client.db(db_name);
        cb(db);
    })
}

const find_history = (db, acct, cb) => {
    const collection = db.collection('histories');
    console.log(acct);
    collection.find({ 'acct': acct }).toArray((err, result) => {
        if (err) {
            console.log(err);
            cb(err);
        } else {
            const user = result[0];   
            cb(user);
        }
    })
}

const create_Log = (db, acct , txid, cb) => {
    const collection = db.collection('histories');
    console.log("create");
    collection.insertOne({
        acct: acct,
        his: [txid]
    }, (result) => {
        cb();
    })
}

class HistoryModule {
    constructor(acct) {
        this.acct = acct;
    }

    Log(txid) {
        db_operate((db) => {
            const collection = db.collection('histories');
            find_history(db, this.acct , (ret) =>{
                if (typeof(ret) === 'undefined') { // 无记录
                    create_Log(db , this.acct , txid, () => {});
                }
                else{
                    ret['his'].push(txid);
                    if(ret['his'].length > 3)
                        ret['his'].shift();
                    collection.updateOne({ 'acct': this.acct }, { $set: { 'his':  ret['his']} });
                }
            })
        })
    }

    GetHistory(cb){
        db_operate((db) => {
            find_history(db, this.acct , (ret) =>{
                cb(ret)
            })
        }) 
    }
    
}

module.exports = HistoryModule;